﻿//  -------------------- iSharePoint -------------------- //
// 
//  Company:	IT Complex, LLC
//  Project:	Smart.Common
//  File name:	CamlQueryExecutor.cs
//  Developer:	Solomatov Igor
//  Created:	15.04.2012
// 
//  -------------------- iSharePoint -------------------- //

using Microsoft.SharePoint;

namespace Smart.Common.Entities
{
	/// <summary>
	/// Caml SharePoint list query executor
	/// </summary>
	public class CamlQueryExecutor : ICamlQueryExecutor
	{
		/// <summary>
		/// Query
		/// </summary>
		public IQueryBuilder<ICamlQueryExecutor> Query { get; set; }

		/// <summary>
		/// Web
		/// </summary>
		public SPWeb Web { get; set; }

		private SiteQuery _siteQuery;

		/// <summary>
		/// Site data query
		/// </summary>
		public SiteQuery SiteQuery
		{
			get { return _siteQuery ?? (_siteQuery = new SiteQuery(this)); }
			set { _siteQuery = value; }
		}

		/// <summary>
		/// SharePoint list
		/// </summary>
		public SPList List { get; set; }

		/// <summary>
		/// Execute query and return all items
		/// </summary>
		public virtual SPListItemCollection GetItems()
		{
			return GetItems(1000000);
		}

		/// <summary>
		/// Execute query and return first item
		/// </summary>
		public virtual SPListItem GetItem()
		{
			var items = GetItems(1);

			return items == null || items.Count <= 0 ? null : items[0];
		}

		/// <summary>
		/// Execute query and return top <paramref name="rowLimit"/> items
		/// </summary>
		public virtual SPListItemCollection GetItems(int rowLimit)
		{
			return SPH.GetFilteredItems(List, Query.FormatQuery(), (uint)rowLimit, Query.GetProperties());
		}

		/// <summary>
		/// Execute <paramref name="query"/> and return top <paramref name="rowLimit"/> items
		/// </summary>
		public virtual SPListItemCollection GetItems(IQueryBuilder query, int rowLimit)
		{
			return SPH.GetFilteredItems(List, query.FormatQuery(), (uint)rowLimit, query.GetProperties());
		}

		public CamlQueryExecutor(SPList list)
		{
			List = list;
		}

		public CamlQueryExecutor(SPWeb web)
		{
			Web = web;
		}
	}
}